package com.linc.facerecognitionsi.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.linc.facerecognitionsi.R;
import com.linc.facerecognitionsi.adapter.ViewpagerAdapter;
import com.linc.facerecognitionsi.metadata.Constants;
import com.linc.facerecognitionsi.utils.ScreenHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity implements ViewPager.OnPageChangeListener {
    private final static String TAG = "MainActivity";
    private ViewPager mViewpager;
    private ArrayList<ImageView> mViews = new ArrayList<ImageView>();
    private ImageView[] mItemPoints;
    private FrameLayout mAdvFl;
    private int currentItem = 0;
    private LinearLayout mItemsLl;
    private ScheduledExecutorService mScheduledExecutorService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mItemsLl = (LinearLayout) findViewById(R.id.itemsll);
        mViewpager = (ViewPager) findViewById(R.id.advertise);

        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height=wm.getDefaultDisplay().getHeight();
        //ad height
        int adHeight = (width * 200) / 500;
        //hegitOffDp是小方块间的间隔加上底部TextView高度的dp值,xml布局文件可做参考，下面计算宽度中的24也类似。
        int heightOffDp = 130;//3 lines 130, 2 lines ?
        //将dp值转为像素
        int heightOffPx= ScreenHelper.dp2px(this, heightOffDp);
        //计算小方块的宽和高
        int buttonWidth=(width-ScreenHelper.dp2px(this, 24))/2;
        int buttonHeight=(int)((height-adHeight-heightOffPx)/2);//more line, modify here
        mAdvFl=(FrameLayout) findViewById(R.id.ad);
        mAdvFl.getLayoutParams().height = adHeight;

        LinearLayout faceCompareLayout,faceCompareWithAliveLayout,
                faceModelingLayout,moreLinearLayout;
        faceModelingLayout=(LinearLayout) findViewById(R.id.ll1);
        faceModelingLayout.getLayoutParams().width = buttonWidth;
        faceModelingLayout.getLayoutParams().height = buttonHeight;
        faceModelingLayout.setOnClickListener(new LinearLayoutOnClickListener(0));

        faceCompareLayout=(LinearLayout) findViewById(R.id.ll2);
        faceCompareLayout.getLayoutParams().width = buttonWidth;
        faceCompareLayout.getLayoutParams().height = buttonHeight;
        faceCompareLayout.setOnClickListener(new LinearLayoutOnClickListener(1));

        faceCompareWithAliveLayout=(LinearLayout) findViewById(R.id.ll3);
        faceCompareWithAliveLayout.getLayoutParams().width = buttonWidth;
        faceCompareWithAliveLayout.getLayoutParams().height = buttonHeight;
        faceCompareWithAliveLayout.setOnClickListener(new LinearLayoutOnClickListener(2));

        moreLinearLayout=(LinearLayout) findViewById(R.id.ll4);
        moreLinearLayout.getLayoutParams().width = buttonWidth;
        moreLinearLayout.getLayoutParams().height = buttonHeight;
        moreLinearLayout.setOnClickListener(new LinearLayoutOnClickListener(3));

        initAdsData();
        mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 5s轮播一次
        mScheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 0,
                5, TimeUnit.SECONDS);
    }

    private class LinearLayoutOnClickListener implements View.OnClickListener {
        private int index = 0;

        public LinearLayoutOnClickListener(int index) {
            super();
            this.index = index;
        }

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (index) {
                case 0:
                    intent.putExtra(Constants.FLAG, Constants.ID_CARD_SCANNING);
//                    intent.setClass(MainActivity.this,InputNameActivity.class);
                    Log.d("TAG", "main thread:"+Thread.currentThread().getName());
                    Log.d("TAG", "mThread:" + Thread.currentThread().getName());
                    break;
                case 1:
                    intent.putExtra(Constants.FLAG, Constants.ID_CARD_FACE_COMPARE);
//                    intent.setClass(MainActivity.this, NameListActivity.class);
                    break;
                case 2://IDCard Number recognize
//                    intent.setClass(MainActivity.this, ChooseMethodActivity.class);
                    break;
                case 3://face build modeling
                    intent.putExtra(Constants.FLAG, Constants.FACE_SCANNING);
//                    intent.setClass(MainActivity.this, InputNameActivity.class);
                    break;
            }
//            MainActivity.this.startActivity(intent);
        }

    }

    public void initAdsData() {
        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT);
        //		String[] urls = {
        //				"http://jisuanqi.jiahuicheng.com/public/index/adv1.jpg",
        //				"http://jisuanqi.jiahuicheng.com/public/index/adv2.jpg",
        //				"http://jisuanqi.jiahuicheng.com/public/index/adv3.jpg",
        //		"http://jisuanqi.jiahuicheng.com/public/index/adv4.jpg" };
        //		for (int i = 0; i < urls.length; i++) {
        //			ImageView imageview = new ImageView(this);
        //			setImageView(imageview, urls[i]);
        //			imageview.setScaleType(ScaleType.FIT_XY);
        //			imageview.setLayoutParams(layoutParams);
        //			imageview.setOnClickListener(new MyOnClickListener(i));
        //			mViews.add(imageview);
        //		}
        int[] ids = {R.mipmap.adv1,R.mipmap.adv2,R.mipmap.adv3,R.mipmap.adv4 };
        for (int i = 0; i < ids.length; i++) {
            ImageView imageview = new ImageView(this);
            imageview.setImageResource(ids[i]);
            imageview.setScaleType(ImageView.ScaleType.FIT_XY);
            imageview.setLayoutParams(layoutParams);
//            imageview.setOnClickListener(new MyOnClickListener(i));//jump to some activity
            mViews.add(imageview);
        }
        ViewpagerAdapter adapter = new ViewpagerAdapter(mViews);
        mViewpager.setAdapter(adapter);
        initAdsItems();
        mViewpager.setOnPageChangeListener(this);
    }

    public void initAdsItems() {
        mItemPoints = new ImageView[mViews.size()];
        for (int i = 0; i < mItemsLl.getChildCount(); i++) {
            mItemPoints[i] = (ImageView) mItemsLl.getChildAt(i);
            mItemPoints[i].setImageResource(R.mipmap.point_normal);
        }
        mItemPoints[currentItem].setImageResource(R.mipmap.point_focus);
    }

    private void setCurrentItem(int position) {
        for (int i = 0; i < mItemsLl.getChildCount(); i++) {
            mItemPoints[i] = (ImageView) mItemsLl.getChildAt(i);
            mItemPoints[i].setImageResource(R.mipmap.point_normal);
        }
        mItemPoints[position].setImageResource(R.mipmap.point_focus);
    }

    private class ViewPagerTask implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % mViews.size();
            handler.obtainMessage().sendToTarget();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mViewpager.setCurrentItem(currentItem);
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "on destroy!");
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            File file=new File(Environment.getExternalStorageDirectory().toString()+"/FaceRecognition/cache/tu/");
            deleteFilesByDirectory(file);
            Intent intent = new Intent(MainActivity.this,OutDialog.class);
            MainActivity.this.startActivityForResult(intent,Constants.REQUEST_CODE );
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==Constants.REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                String result = data.getStringExtra(Constants.RESULT);
                if(Constants.RESULT_OK.equals(result)) {
                    MainActivity.this.finish();
                }else{
                    return;
                }
            }
        }
    }

    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setCurrentItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
